/*
 * Copyright (C) 2011 Dirk Weißenborn, dirk.weissenborn@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weissenborn.colabtex.server.etherpad;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

import com.google.gson.Gson;

/**
 * The Class EtherpadUtils for using the etherpad http api
 */
public class EtherpadUtils {
	
	/** The ini path. */
	String iniPath;
	
	/** The api url. */
	String apiUrl;
	
	/** The api key. */
	String apiKey;
	
	/** The pad url. */
	String padUrl;
	
	/** The read only url. */
	String readOnlyUrl;
	
	/**
	 * Instantiates a new etherpad utils.
	 *
	 * @param ini the ini
	 */
	public EtherpadUtils(String ini) {
		iniPath = ini;
		init();
	}

	/**
	 * Inits the.
	 */
	private void init() {
		try{
		     Properties p = new Properties();
		     p.load(getClass().getClassLoader().getResourceAsStream(iniPath));
		     apiUrl = p.getProperty("apiUrl");
		     apiKey = p.getProperty("apiKey");
		     padUrl = p.getProperty("padUrl");
		     readOnlyUrl = p.getProperty("readOnlyUrl");
	    }
	    catch (Exception e) {
		      System.out.println(e);
	    }
	}
	
	/**
	 * Request.
	 *
	 * @param strings the strings
	 * @return the string
	 */
	private String request(String... strings) {
		String urlS = apiUrl;
		urlS +="/"+strings[0]+"?apikey="+apiKey;
		for (int i = 1; i < strings.length; i++) {
			urlS+="&"+strings[i];
		}
		URL url;
		try {
			url = new URL(urlS);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
		
		String resp = "";
		try {
			  BufferedReader in = new BufferedReader(
			        new InputStreamReader(
			        url.openStream()));

			  String inputLine;

			  while ((inputLine = in.readLine()) != null)
			      resp+=inputLine;

			  in.close();
		} catch (IOException e) {			
			e.printStackTrace();
			return null;
		}	
		
		return resp;
	}
	

	/**
	 * Gets the read only pad url.
	 *
	 * @param padName the pad name
	 * @return the read only pad url
	 */
	public String getReadOnlyPadUrl(String padName) {
		String urlS = readOnlyUrl;
		urlS += getReadOnlyID(padName);
		return urlS;
	}
	
	/**
	 * Gets the pad url.
	 *
	 * @param padName the pad name
	 * @return the pad url
	 */
	public String getPadUrl(String padName) {
		String urlS = padUrl;
		urlS +=padName;
		return urlS;
	}
	//############################groups###########################################
	/**
	 * Creates the group.
	 *
	 * @return the string
	 */
	public String createGroup() {
		String response = request("createGroup");
		Gson gson = new Gson();
		EtherpadGroupResult result = gson.fromJson(response, EtherpadGroupResult.class);
		
		if(result.getCode()>0){
			System.out.println(result.getMessage());
			return null;
		}
		return result.getData().groupID;
	}
	
	/**
	 * Delete group.
	 *
	 * @param groupID the group id
	 */
	public void deleteGroup(String groupID) {
		String response = request("deleteGroup","groupID="+groupID);
		
		Gson gson = new Gson();
		EtherpadNullResult result = gson.fromJson(response, EtherpadNullResult.class);
		
		if(result.getCode()>0)
			System.out.println(result.getMessage());
	}
	
	/**
	 * List pads.
	 *
	 * @param groupID the group id
	 * @return the string[]
	 */
	public String[] listPads(String groupID) {
		String response = request("listPads","groupID="+groupID);
		
		Gson gson = new Gson();
		EtherpadPadListResult result = gson.fromJson(response, EtherpadPadListResult.class);
		
		if(result.getCode()>0){
			System.out.println(result.getMessage());
			return null;
		}
		return result.getData().padIDs;
	}

	/**
	 * Creates the group pad.
	 *
	 * @param groupID the group id
	 * @param padName the pad name
	 * @return the boolean
	 */
	public Boolean createGroupPad(String groupID, String padName) {
		String response = request("createGroupPad","groupID="+groupID,"padName="+padName);
		request("setPublicStatus","padID="+groupID+"$"+padName,"publicStatus=true");
		Gson gson = new Gson();
		EtherpadPadResult result = gson.fromJson(response, EtherpadPadResult.class);
		
		if(result.getCode()>0){
			System.out.println(result.getMessage());
			return false;
		}
		return true;
	}
	
	//#############################Author##############################
	/**
	 * Creates the author.
	 *
	 * @param nickName the nick name
	 * @return the string
	 */
	public String createAuthor(String nickName) {
		String response = request("createAuthor","name="+nickName);
		
		Gson gson = new Gson();
		EtherpadAuthorResult result = gson.fromJson(response, EtherpadAuthorResult.class);
		
		if(result.getCode()>0){
			System.out.println(result.getMessage());
			return null;
		}
		return result.getData().authorID;
	}
	
	/**
	 * Creates the author if not exists for.
	 *
	 * @param name the name
	 * @param nickName the nick name
	 * @return the string
	 */
	public String createAuthorIfNotExistsFor(String name, String nickName) {
		String response = request("createAuthorIfNotExistsFor","authorMapper="+name,"name="+nickName);

		Gson gson = new Gson();
		EtherpadAuthorResult result = gson.fromJson(response, EtherpadAuthorResult.class);
		
		if(result.getCode()>0){
			System.out.println(result.getMessage());
			return null;
		}
		
		return result.getData().authorID;
	}

	//#############################Session#############################
	/*public; String createSession(String groupID, String authorID, String validUntil) {
		EtherpadApiResult response = request("createSession","groupID="+groupID,"authorID="+authorID,"validUntil="+validUntil);
		
		if(response.getCode()>0) {
			System.out.println(response.getMessage());
			return null;
		}
		
		return response.getData().get("sessionID")[0];
	}

	public void deleteSession(String sessionID) {
		EtherpadApiResult response = request("deletSession","sessionID="+sessionID);
		
		if(response.getCode()>0)
			System.out.println(response.getMessage());
	}

	public String[] getSessionInfo(String sessionID) {
		EtherpadApiResult response = request("getSessionInfo","sessionID="+sessionID);
		
		if(response.getCode()>0) {
			System.out.println(response.getMessage());
			return null;
		}
		
		return new String[]{response.getData().get("authorID")[0],
				response.getData().get("groupID")[0],
				response.getData().get("validUntil")[0]};
	}*/
	
	//#############################Pad###################################
	/**
	 * Gets the text.
	 *
	 * @param padID the pad id
	 * @return the text
	 */
	public String getText(String padID) {
		String response = request("getText","padID="+padID);

		Gson gson = new Gson();
		EtherpadTextResult result = gson.fromJson(response, EtherpadTextResult.class);
		
		if(result.getCode()>0) {
			System.out.println(result.getMessage());
			return null;
		}

		return result.getData().text;
	}

	/**
	 * Sets the text.
	 *
	 * @param padID the pad id
	 * @param text the text
	 */
	public void setText(String padID, String text) {
		String response = request("setText","padID="+padID,"text="+text);
		
		Gson gson = new Gson();
		EtherpadNullResult result = gson.fromJson(response, EtherpadNullResult.class);
		
		if(result.getCode()>0)
			System.out.println(result.getMessage());
	}
	
	/*	
	public void createPad(String padID) {
		EtherpadApiResult response = request("createPad","padID="+padID);
		
		if(response.getCode()>0) 
			System.out.println(response.getMessage());
	}
	
	
	public Integer getRevisionsCount(String padID) {
		EtherpadApiResult response = request("getRevisionsCount","padID="+padID);
		
		if(response.getCode()>0) {
			System.out.println(response.getMessage());
			return null;
		}
		
		return Integer.parseInt(response.getData().get("revisions")[0]);
	}*/
	
	/**
	 * Gets the read only id.
	 *
	 * @param padID the pad id
	 * @return the read only id
	 */
	public String getReadOnlyID(String padID) {
		String response = request("getReadOnlyID","padID="+padID);
		
		Gson gson = new Gson();
		EtherpadReadOnlyResult result = gson.fromJson(response, EtherpadReadOnlyResult.class);
		
		if(result.getCode()>0) {
			System.out.println(result.getMessage());
			return null;
		}
		
		return result.getData().readOnlyID;
	}
	
	/**
	 * Delete pad.
	 *
	 * @param padID the pad id
	 */
	public void deletePad(String padID) {
		String response = request("deletePad","padID="+padID);

		Gson gson = new Gson();
		EtherpadNullResult result = gson.fromJson(response, EtherpadNullResult.class);
		
		if(result.getCode()>0)
			System.out.println(result.getMessage());
	}
	/*
	public void setPublicStatus(String padID, Boolean publicStatus) {
		String response = request("setPublicStatus","padID="+padID,"publicStatus="+String.valueOf(publicStatus));
		
		if(response.getCode()>0) 
			System.out.println(response.getMessage());
	}
	
	public Boolean getPublicStatus(String padID) {
		EtherpadApiResult response = request("getPublicStatus","padID="+padID);
		
		if(response.getCode()>0) {
			System.out.println(response.getMessage());
			return null;
		}
		
		return Boolean.valueOf(response.getData().get("publicStatus")[0]);
	}
	
	public void setPassword(String padID, String password) {
		EtherpadApiResult response = request("setPassword","padID="+padID,"password="+password);
		
		if(response.getCode()>0) 
			System.out.println(response.getMessage());
	}
	
	public Boolean isPasswordProtected(String padID) {
		EtherpadApiResult response = request("isPasswordProtected","padID="+padID);
		
		if(response.getCode()>0) {
			System.out.println(response.getMessage());
			return null;
		}
		
		return Boolean.valueOf(response.getData().get("publicStatus")[0]);
	}*/
	
	//###########################Mapping####################################


}
